<?php namespace app\common\controller;

use think\Controller;
use think\Db;
use think\Cache;
use think\Request;

/**
 * 认证及绑定
 */
class AuthAndBind extends Controller{
	
	public $userInfo = '';
	public $userId = '';
	static private $loginInfo = '';
	static private $cacheServiceObj = '';
	
	public function __construct(){
		parent::__construct();
		
		if(empty(self::$cacheServiceObj)) self::$cacheServiceObj = controller("service/Cache");
		$param = $this -> checkParam();		//校验参数
		$this -> checkSign($param);			//验签
		$this -> checkToken($param);		//校验TOKEN
//		$this -> checkAdminPwd();			//校验密码
	}
	
	/**
	 * 删除某个token
	 */
	public function delToken($token = ''){
		$token = (empty($token) || is_null($token) || !$token) ? $_SERVER['HTTP_REQUESTED_T'] : $token;
		$userLoginCacheAll = self::$cacheServiceObj -> getCache('userToken', '');	//获取所有后台用户登陆缓存
		
		if( !empty($userLoginCacheAll) ){
			foreach ($userLoginCacheAll as $k => $v) {
				if( isset($v['loginToken']) && count($v['loginToken']) > 0 ){
					foreach ($v['loginToken'] as $kk => $vv) {
						if( is_array($vv) && count($vv) > 0 ){
							foreach ($vv as $kkk => $vvv) {
								if( $kkk == $token ){
//									删除token
									unset($userLoginCacheAll[$k]['loginToken'][$kk][$kkk]);
									self::$cacheServiceObj -> setCache('userToken', '', $userLoginCacheAll);
									break;
								}
							}
						}
					}
				}
			}
		}
		return ['code'=>'1'];
	}
	
	/*
	 * 校验TOKEN
	 */
	private function checkToken($param){
		$token = $param['token'];
		$userLoginCacheAll = self::$cacheServiceObj -> getCache('userToken', '');	//获取所有后台用户登陆缓存
		
		$outArr['code'] = '40002';
		$tokenRe = FALSE;
		foreach ($userLoginCacheAll as $k => $v) {
			if( isset($v['loginToken']) && count($v['loginToken']) > 0 ){
				foreach ($v['loginToken'] as $kk => $vv) {
					if( is_array($vv) && count($vv) > 0 ){
						foreach ($vv as $kkk => $vvv) {
							if( $kkk == $token ){
								$this -> userId = $v['userId'];
//								$expireTime = $vvv['setTokenTime'] + $vvv['tokenExpireTime'];
								$expireTime = $vvv['tokenExpireTime'];
								
								if( $expireTime <= time() || ($v['userId'] != 1 && $vvv['setTokenTime'] + config("LOGIN_EXPIRE_TIME") <= time()) ){
//								if( $expireTime <= time() ){
//									已到期,删除token
									unset($userLoginCacheAll[$k]['loginToken'][$kk][$kkk]);
									self::$cacheServiceObj -> setCache('userToken', '', $userLoginCacheAll);
								}else{
//									未到期,存储用户信息
									$tokenRe = $v;
									$this -> userInfo = $v;
								}
							}
						}
					}
				}
			}
		}
		if( $param['token'] == '22bec846b4f36eb36a302909158ee2a9' || $tokenRe === FALSE){
//			p($userLoginCacheAll);die;
		}
		if( $tokenRe === FALSE ) returnResults($outArr);	//token不存在或已过期
	}
	
	/**
	 * 验签
	 */
	private function checkSign($param){
		$sign = md5($param['token'] . $param['signTime'] . config('PARAM_KEY'));
		$outArr['code'] = '40002';
		if( $sign != $param['sign'] ){
			p($sign);
			p($param);
			die;
		}
		return $sign != $param['sign'] ? returnResults($outArr) : TRUE;
	}
	
	/**
	 * 校验参数
	 * @param	string		$token		token
	 * @param	string|int	$userId		用户ID(sysUser表ID)
	 * @param	string		$sign		签名+毫秒级时间戳,|分隔(如：abcde|1234567890123)
	 */
	private function checkParam(){
		
		$token = isset($_SERVER['HTTP_REQUESTED_T']) ? $_SERVER['HTTP_REQUESTED_T'] : '';
		$sign = isset($_SERVER['HTTP_REQUESTED_S']) ? $_SERVER['HTTP_REQUESTED_S'] : '';
		if(empty($token) || empty($sign) || empty(explode('|', $sign)[1])){
			$outArr['code'] = '40004';
			returnResults($outArr);
		}
		$sign = explode('|', $sign);
		$param['token'] = $token;					//token
		$param['sign'] = $sign[0];					//签名
		$param['signTime'] = $sign[1];				//签名时间戳
		if( ($param['signTime'] + 1) < time() ){
//			returnResults(['code'=>'40015']);
		}
		return $param;
	}
	
	/**
	 * 获取当前用户职位及权限
	 * @param	string	$userId		用户id	
	 */
	public function getUserPosition(){
		$in['a.userId'] = $this -> userId;
		$in['field'] = ['b.*'];
		$group = controller("service/AuthGroupAccess") -> getJoinAuthgroupMuchData($in);
		if( $group['code'] == '1' ) $group['info'] = $group['info'][0];
		return $group;
	}
	
	/**
	 * 获取当前用户信息
	 */
	public function getUserInfo(){
		$userInfo = controller("service/User") -> getSingleData(['userId'=>$this -> userId]);
		if( !empty($userInfo) ) {
			$userInfo['auth_group'] = Db::table("gd_auth_group_access") -> alias('a') -> join('gd_auth_group b', 'a.group_id = b.id') -> join('gd_auth_data_rules c', 'c.id = b.data_rules') -> field(['b.name', 'b.data_rules', 'c.path', 'c.title']) -> where(['a.uid'=>$this -> userId]) -> find();
		}
		if( isset($userInfo['info']) && !empty($userInfo['auth_group']) && $userInfo['auth_group']['path'] == 'STORE' ) {
			$userInfo['shop'] = Db::table("gd_shop") -> where(['create_user_id'=>$userInfo['info']['id']]) -> find();
		}
		if( isset($userInfo['info']) && !empty($userInfo['auth_group']) && $userInfo['auth_group']['path'] == 'REGION' ) {
			$userInfo['shop'] = Db::table("gd_user") -> alias('a') -> join('gd_shop b', 'a.id = b.create_user_id') -> field(['b.*']) -> where(['a.type'=>3, 'a.referrer_id'=>$userInfo['info']['id']]) -> select();
		}
		return $userInfo;
	}
	
	/**
	 * 校验密码
	 */
//	private function checkAdminPwd(){
//		$where['id'] = $this -> userId;
//		$userInfo = controller("service/Admin") -> getSingleData(['userId'=>$this -> userId]);
//		if( strtotime($userInfo['password_update_time']) + 86400 * 30 < time() ){
//			returnResults(['code'=>-1, 'mes'=>'密码失效'])
//		}
//	}
	
	/**
	 * 获取当前用户
	 */
//	public function getDistrictInfo(){
//		$in['districtId'] = config("ZX_DISTRICT_ID");
//		$districtInfo = controller("service/District") -> getSingleData($in);
//		return $districtInfo;
//	}
}

?>